package com.xtedu.examproject.controller;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.xtedu.examproject.entity.Teacher;
import com.xtedu.examproject.entity.paperTemplates;
import com.xtedu.examproject.service.PaperTemplatesService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/paperTemplatesServlet")
public class PaperTemplatesServlet extends HttpServlet {
    private PaperTemplatesService paperTemplatesService;

    public void init() {
        paperTemplatesService = new PaperTemplatesService();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");

        // 获取路径信息
        String pathInfo = req.getPathInfo();
        // 处理路径信息
        String path = (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) ? "/" : pathInfo;
        try {
            switch (path) {
                case "/addPaperTemplates":
                    addPaperTemplates(req, resp);
                    break;
                case "/deletePaperTemplates":
                    deletePaperTemplates(req, resp);
                    break;
                case "/updateTemplates":
                    updateTemplates(req, resp);
                    break;
                case "/selectTemplateById":
                    selectTemplateById(req, resp);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 获取路径信息
        String pathInfo = req.getPathInfo();

        try {
            if (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) {

            } else if (pathInfo.equals("/addPaperTemplates")) {
                addPaperTemplates(req, resp);
            } else if (pathInfo.equals("/deletePaperTemplates")) {
                deletePaperTemplates(req, resp);
            } else if (pathInfo.equals("/updateTemplates")) {
                updateTemplates(req, resp);
            } else if (pathInfo.equals("/selectTemplateById")) {
                selectTemplateById(req, resp);
            }
        } catch (Exception e) {
            System.err.println("处理POST请求时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 添加模板
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void addPaperTemplates(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 添加请求体非空判断
            if (sb.toString().trim().isEmpty()) {
                JSONObject responseJson = new JSONObject();
                responseJson.put("success", false);
                responseJson.put("message", "请求数据不能为空");
                resp.getWriter().write(responseJson.toString());
                return;
            }

            // 解析JSON数据
            Gson gson = new Gson();
            paperTemplates paperTemplates = gson.fromJson(sb.toString(), paperTemplates.class);
            paperTemplatesService.insert(paperTemplates);

            // 返回成功响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", true);
            responseJson.put("message", "老师信息添加成功");
            resp.getWriter().write(responseJson.toString());

        } catch (Exception e) {
            // 返回错误响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "添加老师信息失败: " + e.getMessage());
            resp.getWriter().write(responseJson.toString());
        }
    }

    /**
     * 删除模板
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    public void deletePaperTemplates(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            // 设置响应类型为JSON
            resp.setContentType("application/json;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");

            // 获取要删除的课程ID
            String templateIdStr = req.getParameter("id");

            // 检查课程ID是否为空
            if (templateIdStr != null && !templateIdStr.isEmpty()) {
                try {
                    int templateId = Integer.parseInt(templateIdStr);

                    // 调用service层方法删除课程
                    boolean deleted = paperTemplatesService.deleteTemplateById(templateId);

                    // 返回JSON响应
                    if (deleted) {
                        resp.getWriter().write("{\"success\":true,\"message\":\"课程删除成功\"}");
                    } else {
                        resp.getWriter().write("{\"success\":false,\"message\":\"课程删除失败，可能课程不存在\"}");
                    }
                } catch (NumberFormatException e) {
                    resp.getWriter().write("{\"success\":false,\"message\":\"课程ID格式错误\"}");
                }
            } else {
                resp.getWriter().write("{\"success\":false,\"message\":\"无效的课程ID\"}");
            }
        } catch (Exception e) {
            System.err.println("删除课程时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 编辑模板信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     */
    public void updateTemplates(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 添加请求体非空判断
            if (sb.toString().trim().isEmpty()) {
                JSONObject responseJson = new JSONObject();
                responseJson.put("success", false);
                responseJson.put("message", "请求数据不能为空");
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(responseJson.toString());
                return;
            }

            // 解析JSON数据
            Gson gson = new Gson();
            paperTemplates template = gson.fromJson(sb.toString(), paperTemplates.class);

            // 添加对象非空判断
            if (template == null) {
                JSONObject responseJson = new JSONObject();
                responseJson.put("success", false);
                responseJson.put("message", "解析请求数据失败");
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(responseJson.toString());
                return;
            }

            // 检查必要字段是否为空
            if (template.getId() <= 0 ||
                    template.getTemplateName() == null || template.getTemplateName().trim().isEmpty() ||
                    template.getDescription() == null || template.getDescription().trim().isEmpty()) {

                // 返回错误响应
                JSONObject responseJson = new JSONObject();
                responseJson.put("success", false);
                responseJson.put("message", "所有字段不能为空");
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(responseJson.toString());
                return;
            }

            // 调用service层更新方法
            boolean updated = paperTemplatesService.updatePaperTemplates(template);

            // 返回响应
            JSONObject responseJson = new JSONObject();
            if (updated) {
                responseJson.put("success", true);
                responseJson.put("message", "模板信息更新成功");
            } else {
                responseJson.put("success", false);
                responseJson.put("message", "模板信息更新失败");
            }

            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(responseJson.toString());

        } catch (Exception e) {
            // 处理其他异常
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "更新模板信息失败: " + e.getMessage());
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(responseJson.toString());
        }
    }

    /**
     * 查询模板
     * 根据id来查询
     *
     * @param req
     * @param resp
     * @throws ServletException
     */
    public void selectTemplateById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 设置响应类型为JSON
            resp.setContentType("application/json;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");

            // 获取并验证模板ID参数
            String templateIdStr = req.getParameter("id");

            // 检查ID参数是否为空
            if (templateIdStr == null || templateIdStr.trim().isEmpty()) {
                resp.getWriter().write("{\"error\":\"模板ID不能为空\"}");
                return;
            }

            try {
                int templateId = Integer.parseInt(templateIdStr);

                // 调用service层方法查询模板
                paperTemplates paperTemplates = paperTemplatesService.findTemplateById(templateId);

                // 返回查询结果
                if (paperTemplates != null) {
                    resp.getWriter().write(new Gson().toJson(paperTemplates));
                } else {
                    resp.getWriter().write("{\"error\":\"未找到指定ID的模板\"}");
                }
            } catch (NumberFormatException e) {
                resp.getWriter().write("{\"error\":\"模板ID格式错误\"}");
            } catch (Exception e) {
                resp.getWriter().write("{\"error\":\"查询模板信息失败: " + e.getMessage() + "\"}");
            }
        } catch (Exception e) {
            e.printStackTrace();
            resp.getWriter().write("{\"error\":\"系统错误\"}");
        }
    }
}
